<?	/*
	// File:	functions.inc.php
	// Purpose:	web-cp server functions (API)
	// Creation:	2002-02-28
	// Author:	Felix <webmaster@can-host.com>
	*/
// system file update function.
function updatesys($type) {
	GLOBAL $cfg, $remapmail, $restarthttp, $restartmail, $restartdns, $echo;

	// Updating system files is done by the module_sys() function of each module
	//
	//  For example bind_sys() updates the bind files, apache_sys() does its job
	//  Note: I am unsure if the DNS Modules check that DNS is enabled before running
		
	// Modules
	// examples: server:domain:sys, server:user:sys
	call_hook('server:'.$type.':sys', $data);
	
} // end of system file function

   
// domain and user system manipulation
function webcp($type,$data) {
	GLOBAL $cfg, $restarthttp, $restartdns, $echo;
	//
	// Include service 'modules'
	$libpath = $cfg['basedir']."/server/lib/";
	
	// Apache Server-side modules
	$tmp = explode(',',$cfg['sslang']);
	foreach($tmp AS $val) {
		// Webware Support
		if ($val == 'webware')
			include($libpath."webware.wcp.phps");
	}

	// UW-IMAP
	if ($cfg['uwimap'])
		include($libpath."uw-imap.wcp.phps");

	// PureFTPd
	if ($cfg['ftpserver'] == 'pureftpd')
		include($libpath."pureftpd.wcp.phps");
		
	// DNS management
	//
	// Moved to bind.mod.phps
	//if ($cfg['dns_system'] == 'bind')
	//	include($libpath."bind.wcp.phps");
	if ($cfg['dns_system'] == 'mail')
		include($libpath."dnsmail.wcp.phps");
	elseif ($cfg['dns_system'] == 'tinydns')
		include($libpath."tinydns.wcp.phps");
	elseif ($cfg['dns_system'] == 'mydns')
		include($libpath."mydns.wcp.phps");
	elseif ($cfg['dns_system'] == 'pdns')
		include($libpath."pdns.wcp.phps");
		
	// Creation of domains on the system
	include($libpath."domain.wcp.phps");
	
	// Database Update
	include($libpath."mysql.wcp.phps");
	
	// Modules
	// examples: server:domain:update, server:user:create
	call_hook('server:'.$type.':'.$data['action'], $data);
	
	// SMTP
	if ($cfg['mailserver'] == 'virtualqmail')
		include($libpath."virtualqmail.wcp.phps");
	elseif ($cfg['mailserver'] == 'exim4')
		include($libpath.'exim4.wcp.phps');
	// Moved to module unix-users.mod.phps
	//elseif ($cfg['mailserver'] == 'sendmail')
	//	include($libpath.'sendmail.wcp.phps');
	
        // Clean up properties
	if($data['action']=='remove') {
		if($type='user') {
			mysql_query("DELETE FROM `properties` WHERE `user` = '".$data['username']."' AND `id` = '".$data['id']."'");
		} elseif($type='domain') {
			mysql_query("DELETE FROM `properties` WHERE `id` = '".$data['id']."'");
		}
	}
}

// function to restart all services / reload their config under 'any' OS
// only restart what's necessary
function reload_services() {
	GLOBAL $cfg, $echo, $remapmail, $restartmail, $restarthttp, $restartdns;
	
	// Check signals to restart whats needed (or remap sendmail)
	if ($remapmail AND !$restartmail) {
		// interactive dump
		webcp_log(3,0,'webcp.php',"Remapping Mail",0,$echo);
		
		if ($cfg['mailserver'] == 'sendmail') {
			if ($cfg['os'] == 'linux') {
				exec($cfg['prog']['nalias']." > /dev/null 2>&1");
				exec($cfg['prog']['makemap']." hash ".$cfg['mail_virtuser']." < ".$cfg['mail_virtuser']." > /dev/null 2>&1");
				exec($cfg['prog']['makemap']." hash ".$cfg['mail_access']." < ".$cfg['mail_access']." > /dev/null 2>&1");
			}
			elseif ($cfg["os"] == "freebsd"){
				$pwd = getcwd();
				chdir("/etc/mail");
				exec($cfg['prog']['make']." maps > /dev/null 2>&1");
				exec($cfg['prog']['make']." aliases > /dev/null 2>&1");
				chdir($pwd);
			}
		}
		
	}
	if ($restarthttp) {
		// interactive dump
		webcp_log(3,0,'webcp.php',"Restarting HTTP",0,$echo);
		exec($cfg['init']['httpd']." restart");
			
	}
	if ($restartdns) {
		// interactive dump
		webcp_log(3,0,'webcp.php',"Restarting DNS",0,$echo);
		
		switch($cfg["dns_system"]){
			case 'bind':
			case 'mydns':
			case 'pdns':
				if ($cfg['os'] == 'linux')
					exec($cfg['init'][$cfg['dns_system']]." restart");
				elseif ($cfg["os"] == "freebsd"){
					exec("/bin/kill -HUP `cat ".$cfg['spid'][$cfg['dns_system']]."` > /dev/null 2>&1");
				}
				break;
			case 'tinydns':
				$pwd = getcwd();
				chdir($cfg["tinydns_dir"]."/root");
				exec("make",$dummy);
				chdir($pwd);
				break;
		}
	}
	if ($restartmail) {
		// interactive dump
		webcp_log(3,0,'webcp.php',"Restarting Mail",0,$echo);
		
		if ($cfg['os'] == 'linux') {
			exec($cfg['init'][$cfg['mailserver']]." stop");
			sleep(1);
			exec('id=`ps aux |grep '.$cfg['mailserver'].' |grep -v grep |cut -c 8-15` && test $id && kill $id');
			exec($cfg['init'][$cfg['mailserver']]." start");
		}
		elseif ($cfg["os"] == "freebsd"){
			$pwd = getcwd();
			chdir("/etc/mail");
			exec($cfg['prog']['make']." restart > /dev/null 2>&1");
			chdir($pwd);
		}
	}
	
	// Re-initialize
	$remapmail = FALSE;
	$restarthttp = FALSE;
	$restartdns = FALSE;
	$restartmail = FALSE;
}

// Recursive copy
function cp($dirsource, $dirdest) {
	
	if(is_dir($dirsource)) {
		$dir_handle=opendir($dirsource);
	}
	mkdir($dirdest."/".$dirsource, 0750);
	while($file=readdir($dir_handle)) {
		if($file!="." && $file!="..") {
			if(!is_dir($dirsource."/".$file)) {
				copy ($dirsource."/".$file, $dirdest."/".$dirsource."/".$file);
			} else {
				cp($dirsource."/".$file, $dirdest);
			}
		}
	}
	closedir($dir_handle);
	return true;
}

// Recursive delete
function rm($fileglob) {
	
	if (is_string($fileglob)) {
       if (is_file($fileglob)) {
           return unlink($fileglob);
       } else if (is_dir($fileglob)) {
           $ok = rm("$fileglob/*");
           if (! $ok) {
               return false;
           }
           return @rmdir($fileglob);
       } else {
           $matching = glob($fileglob);
           if ($matching === false) {
               return false;
           }
           $rcs = array_map('rm', $matching);
           if (in_array(false, $rcs)) {
               return false;
           }
       }
   } else if (is_array($fileglob)) {
       $rcs = array_map('rm', $fileglob);
       if (in_array(false, $rcs)) {
           return false;
       }
   } else {
       return false;
   }
   return true;
}

// Recursive chown & chgrp
function chown_chgrp($mypath, $uid, $gid) {

	$d = opendir ($mypath) ;
	while(($file = readdir($d)) !== false) {
       if ($file != "." && $file != "..") {
           $typepath = $mypath . "/" . $file ;
           if (filetype ($typepath) == 'dir') {
               chown_chgrp ($typepath, $uid, $gid);
           }
           chown($typepath, $uid);
           chgrp($typepath, $gid);
       }
   }
}

function file_edit($pattern, $replace, $file_name) {
/* replace all matches in a file according to a perl compatible
 * regular expression. */
	if ($fp = fopen($file_name, 'r+b')) {
		flock($fp, LOCK_EX);
		/* read file into variable */
		$content = '';
		while (!feof($fp)) {
			$content .= fread($fp, 4096);
		}
		/* debated going straight to preg_replace() for speed reasons
		 * but decided it was too useful to know if it was successful
		 * and how many replaces took place. */
		$result = preg_match_all($pattern, $content, $match);
		if ($result > 0) {
			/* replace strings in the current file using regex */
			$content = preg_replace($pattern, $replace, $content, $result);
		}
		/* go back to start of file, write new data, then
		 * wipe out any data left over from before */
		rewind($fp);
		fwrite($fp, $content, strlen($content));
		fflush($fp);
		ftruncate($fp, ftell($fp));
		flock($fp, LOCK_UN);
		fclose($fp);
	} else {
		$result = false;
	}
	return $result;
}
function file_append($append, $file_name) {
/* Add to the end of a file */
	if ($fp = fopen($file_name, 'ab')) {
		flock($fp, LOCK_EX);
		if (fwrite($fp, $append, strlen($append)) !== false) {
			$result = true;
		} else {
			$result = false;
		}
		
		flock($fp, LOCK_UN);
		fclose($fp);
	} else {
		$result = false;
	}
	return $result;
}
function user_exists($username) {
	// Check for existing user
	// Use getent if it is defined and grep otherwise
	if ($cfg['prog']['getent'] != "") {
		$userexists = (exec($cfg['prog']['getent']." passwd '".$username."'") != "") ? true : false;
	} else {
		$userexists = (exec("grep '^".$username.":' /etc/passwd") != "") ? true : false;
	}
	return $userexists;
}
function updateticketfromemail($ID, $FirstName, $LastName, $ticket_address, $ticket_subject, $ticket_body, $ticket_IP, $fromhost, $priorityid, $ticket_date) {
	// select the ticket information from the database
	$SQL = "select max(id) as maxid from helpdesk_ticket_followups WHERE ticketid = $ID";
	$res = mysql_query($SQL);
	if ($row = mysql_fetch_array && $row["maxid"] != "") {
		$SQL = "SELECT helpdesk_tickets.ticketid, helpdesk_ticket_followups.statusid, helpdesk_ticket_followups.escalationid FROM helpdesk_tickets inner join helpdesk_ticket_followups ON helpdesk_tickets.id = helpdesk_ticket_followups.ticketid WHERE helpdesk_ticket_followups.id = ".$row["maxid"]." AND id = $ID";
	} else {
		$SQL = "SELECT ticketid, statusid, escalationid FROM helpdesk_tickets WHERE id = $ID";
	}
	$res = mysql_query($SQL);
	$row = mysql_fetch_array($res);
	$ticketid = $row["ticketid"];
	
	$SQL = "INSERT INTO helpdesk_ticket_followups(firstname, lastname, email, subject, body, ipaddress, domain, priorityid, submissiondate, ticketid, statusid, escalationid)
    		VALUES('$FirstName', '$LastName', '$ticket_address', '".addslashes($ticket_subject)."', '".addslashes($ticket_body)."', '$ticket_IP', '$fromhost', '$priorityid', '$ticket_date', $ID, ".$row["statusid"].", ".$row["escalationid"].")";
	if (mysql_query($SQL)) {
		mail($ticket_address, "Support Ticket Updated: $ticket_subject TN$ticketid", "We have received the following technical support ticket update from you.\r\nYou can view this ticket online at http://www.someurl.com/ticket.php?ticket=$ticketid\r\n\r\n-----------Ticket Follows-----------\r\n".$ticket_body, "From: ".$cfg['helpdesk_POP_email']."\r\n");
		return $ticketid;
	} else {
		return false;
	}
}
	
function createticketfromemail($FirstName, $LastName, $ticket_address, $ticket_subject, $ticket_body, $ticket_IP, $fromhost, $priorityid, $ticket_date) {
	// generate the ticketid
	do {
		srand((double)microtime()*1000000);
		$ticketid = rand(100000000, 999999999);
	
		// check to ensure the ticketid doesn't already exist
		$SQL = "SELECT id FROM helpdesk_tickets WHERE ticketid = '$ticketid'";
		$res = mysql_query($SQL);
	} while (mysql_num_rows($res));
	
	// insert the ticket into the database
	$SQL = "INSERT INTO helpdesk_tickets(firstname, lastname, email, subject, body, ipaddress, domain, priorityid, submissiondate, ticketid)
			VALUES('$FirstName', '$LastName', '$ticket_address', '".addslashes($ticket_subject)."', '".addslashes($ticket_body)."', '$ticket_IP', '$fromhost', '$priorityid', '$ticket_date', '$ticketid')";
			echo $SQL;
	if (mysql_query($SQL)) {
		mail($ticket_address, "Support Ticket Created: $ticket_subject TN$ticketid", "We have received the following technical support ticket from you.\r\nYou can view this ticket online at http://www.someurl.com/ticket.php?ticket=$ticketid\r\n\r\n-----------Ticket Follows-----------\r\n".$ticket_body, "From: ".$cfg['helpdesk_POP_email']."\r\n");
		return true;
	} else {
		webcp_log(1,0,'tt',"ticket failed to insert - $SQL",0);
		return false;
	}
}
?>
